/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

#include<vector>
#include<iostream>
#include<cmath>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


// 问题: pathsum加不进去数据，size一直为0

// 经过调试得：因为每次之后root->left或者root->right不为空时才调用dfs，所以永远都不会进入
// if(!root)内部，以至于不会讲到叶子节点的路径和加到vector中.
class Solution {
public:
    vector<int> pathsum;

    void dfs(TreeNode* root, int cur){
        if (!root) {
            cout << "!root" << endl;
            pathsum.push_back(cur);
            return;
        }

        if (root->left) {
            dfs(root->left, cur + root->left->val);
        }
        if (root->right) {
            dfs(root->right, cur + root->right->val);
        }
    }

    bool hasPathSum(TreeNode* root, int targetSum) {
        if (!root) return targetSum==0;

        dfs(root, root->val);

        cout << "size:" << pathsum.size() << endl;
        for (auto &x: pathsum){
            // if (x == targetSum) return true;
            cout << x << endl;
        }
        return false;
    }
};


int main() {
    // 构造二叉树
    //       5
    //      / \
    //     4   8
    //    /   / \
    //   11  13  4
    //  /  \      \
    // 7    2      1
    TreeNode* root = new TreeNode(5);
    root->left = new TreeNode(4);
    root->right = new TreeNode(8);
    root->left->left = new TreeNode(11);
    root->right->left = new TreeNode(13);
    root->right->right = new TreeNode(4);
    root->left->left->left = new TreeNode(7);
    root->left->left->right = new TreeNode(2);
    root->right->right->right = new TreeNode(1);

    Solution s;
    int targetSum = 22;

    bool res = s.hasPathSum(root, targetSum);
    cout << "hasPathSum: " << (res ? "true" : "false") << endl;

    // 释放内存
    delete root->left->left->left;
    delete root->left->left->right;
    delete root->left->left;
    delete root->left;
    delete root->right->left;
    delete root->right->right->right;
    delete root->right->right;
    delete root->right;
    delete root;

    return 0;
}